#include "search_tree_widget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QKeyEvent>
#include "edit_node_dialog.h"
#include "dealer_handler.h"
#include "state_group.h"
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QDebug>
#include <QSqlQuery>
#include "database_manager.h"
SearchTreeWidget::SearchTreeWidget(QWidget *parent)
    : QWidget(parent),
      tree_widget_(new QTreeWidget(this)),
      search_input_(new QLineEdit(this)),
      search_label_(new QLabel("搜索", this)),
      context_menu_enabled_(true),
      shortcut_enabled_(true),
      double_click_enabled_(true),
      dealer_handler_(DealerHandler::getInstance())
{
    // 设置搜索框布局
    QHBoxLayout *search_layout = new QHBoxLayout;
    search_layout->setContentsMargins(5, 0, 5, 0);
    search_layout->addWidget(search_label_);
    search_layout->addWidget(search_input_);

    // 设置树形控件
    tree_widget_->setObjectName("subtationTree");
    tree_widget_->setColumnCount(1);
    tree_widget_->setAlternatingRowColors(false);              // 启用交替行颜色
    tree_widget_->setAnimated(false);                          // 禁用动画效果
    tree_widget_->setExpandsOnDoubleClick(false);              // 禁用双击展开
    tree_widget_->setContextMenuPolicy(Qt::CustomContextMenu); // 启用自定义右键菜单
    tree_widget_->setHeaderHidden(true);                       // 隐藏表头
    tree_widget_->setItemsExpandable(false);                   // 禁用展开/折叠
    tree_widget_->setIndentation(12);

    // 设置主布局
    QVBoxLayout *main_layout = new QVBoxLayout(this);
    main_layout->setSpacing(5);
    main_layout->setContentsMargins(5, 0, 0, 0);
    main_layout->addLayout(search_layout);
    main_layout->addWidget(tree_widget_);

    // 连接信号槽
    connect(search_input_, &QLineEdit::textChanged, this, &SearchTreeWidget::onSearchTextChanged);
    connect(tree_widget_, &QTreeWidget::itemDoubleClicked, this, &SearchTreeWidget::onItemDoubleClicked);
    connect(tree_widget_, &QTreeWidget::itemClicked, this, &SearchTreeWidget::onItemClicked);
    connect(tree_widget_, &QTreeWidget::customContextMenuRequested, this, &SearchTreeWidget::onTreeContextMenu);
    connect(dealer_handler_, &DealerHandler::messageReceived, this, &SearchTreeWidget::onNetworkMessageReceived);

    // 请求所有子站
    dealer_handler_->sendRequest("select-all-substation", "");
}

SearchTreeWidget::~SearchTreeWidget()
{
}

void SearchTreeWidget::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
}

QTreeWidget *SearchTreeWidget::treeWidget() const
{
    return tree_widget_;
}

QLineEdit *SearchTreeWidget::searchInput() const
{
    return search_input_;
}

void SearchTreeWidget::setHeaderLabel(const QString &label)
{
    tree_widget_->setHeaderLabel(label);
}

void SearchTreeWidget::setSearchPlaceholderText(const QString &text)
{
    search_input_->setPlaceholderText(text);
}

void SearchTreeWidget::setContextMenuEnabled(bool enable)
{
    context_menu_enabled_ = enable;
}

void SearchTreeWidget::setShortcutEnabled(bool enable)
{
    shortcut_enabled_ = enable;
}

void SearchTreeWidget::setDoubleClickEnabled(bool enable)
{
    double_click_enabled_ = enable;
}

void SearchTreeWidget::refreshTree()
{
    // 清空树形控件
    clearTree();

    // 添加所有节点
    addNodes();
    // 展开所有节点
    tree_widget_->expandAll();
}

void SearchTreeWidget::clearTree()
{
    tree_widget_->clear();
}

void SearchTreeWidget::addNodes()
{
    // 遍历所有主站组
    for (auto group : state_group_vec_)
    {
        if (!group || !group->stateInfo())
        {
            continue;
        }

        // 创建根节点
        QTreeWidgetItem *root_item = new QTreeWidgetItem(tree_widget_);
        root_item->setText(0, group->stateInfo()->stateName());
        // 使用主站ID作为根节点数据
        root_item->setData(0, Qt::UserRole, QVariant(static_cast<qlonglong>(group->stateInfo()->id())));

        // 添加该主站下的所有子站
        const QVector<StateInfo *> &child_states = group->stateInfosVec();
        for (auto state_info : child_states)
        {
            if (!state_info)
            {
                continue;
            }

            QTreeWidgetItem *child_item = new QTreeWidgetItem(root_item);
            child_item->setText(0, state_info->stateName());
            // 存储子站ID
            child_item->setData(0, Qt::UserRole, QVariant(static_cast<qlonglong>(state_info->id())));
        }
    }

    if(!search_input_->text().isEmpty())
    {
        QString search_text = search_input_->text();
        onSearchTextChanged(search_text);
    }
}

void SearchTreeWidget::onTreeContextMenu(const QPoint &pos)
{
    if (!context_menu_enabled_)
    {
        return;
    }

    QTreeWidgetItem *item = tree_widget_->itemAt(pos);
    if (!item)
    {
        return;
    }

    QMenu menu(this);
    QAction *addAction = menu.addAction("新增");
    QAction *editAction = menu.addAction("编辑");
    menu.addSeparator();
    QAction *deleteAction = menu.addAction("删除");

    // 获取当前节点的ID
    int64_t node_id = item->data(0, Qt::UserRole).toLongLong();
    StateInfo *current_state = nullptr;

    // 遍历所有主站组查找对应的状态信息
    for (auto group : state_group_vec_)
    {
        if (group->stateInfo()->id() == node_id)
        {
            current_state = group->stateInfo();
            break;
        }

        // 检查子站
        for (auto child_state : group->stateInfosVec())
        {
            if (child_state->id() == node_id)
            {
                current_state = child_state;
                break;
            }
        }

        if (current_state)
        {
            break;
        }
    }

    // 如果是子站，禁用新增操作
    if (current_state && current_state->parentId() != 0)
    {
        addAction->setEnabled(false);
    }
    // 如果是主站，禁用删除操作
    if (current_state && current_state->parentId() == 0)
    {
        deleteAction->setEnabled(false);
    }

    QAction *selectedAction = menu.exec(tree_widget_->viewport()->mapToGlobal(pos));
    if (selectedAction == addAction)
    {
        // 只有在主站上才能添加子站
        if (current_state && current_state->parentId() == 0)
        {
            addNode(current_state);
        }
    }
    else if (selectedAction == editAction)
    {
        editNode(current_state);
    }
    else if (selectedAction == deleteAction)
    {
        deleteNode(current_state);
    }
}

void SearchTreeWidget::onSearchTextChanged(const QString &text)
{
    // 实现搜索功能
    for(int i = 0; i < tree_widget_->topLevelItemCount(); i++)
    {
        QTreeWidgetItem *item = tree_widget_->topLevelItem(i);
        for(int j = 0; j < item->childCount(); j++)
        {
            QTreeWidgetItem *child_item = item->child(j);
            bool match = child_item->text(0).contains(text, Qt::CaseInsensitive);
            child_item->setHidden(!match);
        }
    }

    // 发送搜索文本变化信号
    emit searchTextChanged(text);
}

bool SearchTreeWidget::editNode(StateInfo *state_info)
{
    if (!state_info)
    {
        return false;
    }

    // 创建并显示编辑对话框
    EditNodeDialog dialog(state_info, this);
    if (dialog.exec() == QDialog::Accepted)
    {
        // 发送更新子站请求
        QString query_json = state_info->toJson();
        dealer_handler_->sendRequest("update-substation", query_json);
        return true;
    }

    return false;
}

bool SearchTreeWidget::addNode(StateInfo *parent_state)
{
    if (!parent_state)
    {
        return false;
    }

    // 创建新的状态信息对象
    StateInfo *new_state_info = new StateInfo();
    // 设置父节点ID
    new_state_info->setParentId(parent_state->id());

    // 创建并显示编辑对话框
    EditNodeDialog dialog(new_state_info, this);
    if (dialog.exec() == QDialog::Accepted)
    {
        // 发送新增子站请求
        QString query_json = new_state_info->toJson();
        dealer_handler_->sendRequest("add-substation", query_json);
        return true;
    }

    // 如果对话框被取消，删除新创建的状态信息对象
    delete new_state_info;
    return false;
}

bool SearchTreeWidget::deleteNode(StateInfo *state_info)
{
    if (!state_info || state_info->parentId() == 0)
    {
        return false;
    }

    // 确认对话框
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认删除",
                                  "确定要删除选中的节点吗？",
                                  QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes)
    {
        // 先保存要删除的StateInfo对象
        QString json_data = state_info->toJson();
        // 发送删除子站请求
        dealer_handler_->sendRequest("delete-substation", json_data);
        return true;
    }

    return false;
}

void SearchTreeWidget::onItemDoubleClicked(QTreeWidgetItem *item, int column)
{
    if (!double_click_enabled_)
    {
        return;
    }

    if (!item)
    {
        return;
    }

    // 获取当前节点的ID
    int64_t node_id = item->data(0, Qt::UserRole).toLongLong();
    StateInfo *current_state = nullptr;

    // 遍历所有主站组查找对应的状态信息
    for (auto group : state_group_vec_)
    {
        if (group->stateInfo()->id() == node_id)
        {
            current_state = group->stateInfo();
            break;
        }

        // 检查子站
        for (auto child_state : group->stateInfosVec())
        {
            if (child_state->id() == node_id)
            {
                current_state = child_state;
                break;
            }
        }

        if (current_state)
        {
            break;
        }
    }

    if (!current_state)
    {
        return;
    }

    emit itemDoubleClicked(*current_state);
    editNode(current_state);
}

void SearchTreeWidget::onItemClicked(QTreeWidgetItem *item, int column)
{
    if (!item)
    {
        return;
    }

    int64_t node_id = item->data(0, Qt::UserRole).toLongLong();
    StateInfo *state_info = nullptr;

    // 遍历所有主站组查找对应的状态信息
    for (auto group : state_group_vec_)
    {
        if (group->stateInfo()->id() == node_id)
        {
            state_info = group->stateInfo();
            break;
        }

        // 检查子站
        for (auto child_state : group->stateInfosVec())
        {
            if (child_state->id() == node_id)
            {
                state_info = child_state;
                break;
            }
        }

        if (state_info)
        {
            break;
        }
    }

    if (!state_info)
    {
        return;
    }
    emit itemClicked(*state_info);
}

void SearchTreeWidget::onNetworkMessageReceived(const QString &method, const QString &body, bool is_error)
{
    if (is_error)
    {
        return;
    }

    if (method == "select-all-substation")
    {
        // 清空现有数据
        for (auto group : state_group_vec_)
        {
            delete group;
        }
        state_group_vec_.clear();

        // 解析 JSON 数据
        QJsonDocument doc = QJsonDocument::fromJson(body.toUtf8());
        if (!doc.isArray())
        {
            return;
        }

        QJsonArray array = doc.array();

        // 第一次遍历：创建所有主站组
        for (const QJsonValue &value : array)
        {
            QJsonObject obj = value.toObject();
            if (obj["pid"].toInt() == 0) // 主站
            {
                int64_t id = obj["id"].toVariant().toLongLong();
                QString host = obj["host"].toString();
                QString description = obj["description"].toString();
                int port = obj["port"].toInt();

                StateGroup *group = new StateGroup(id, host, description, port);
                state_group_vec_.append(group);
            }
        }

        // 第二次遍历：添加子站到对应的主站组
        for (const QJsonValue &value : array)
        {
            QJsonObject obj = value.toObject();
            if (obj["pid"].toInt() != 0) // 子站
            {
                int64_t id = obj["id"].toVariant().toLongLong();
                int64_t pid = obj["pid"].toVariant().toLongLong();
                QString host = obj["host"].toString();
                QString description = obj["description"].toString();
                int port = obj["port"].toInt();
                for (auto group : state_group_vec_)
                {
                    if (group->stateInfo()->id() == pid)
                    {
                        group->appendStateInfo(id, host, description, port);
                    }
                }
            }
        }

        // 初始化点表地址配置
        for (auto group : state_group_vec_)
        {
            for (auto state_info : group->stateInfosVec())
            {
                DatabaseManager::initPointAddressConfig(state_info->id());
            }
        }

        // 刷新树形控件显示
        refreshTree();
    }

    if (method == "add-substation")
    {
        QJsonDocument doc = QJsonDocument::fromJson(body.toUtf8());
        if (!doc.isObject())
        {
            qDebug() << "Invalid JSON data format";
            return;
        }

        QJsonObject obj = doc.object();

        int pid = obj["pid"].toInt();
        int id = obj["id"].toInt();

        if (id > 0)
        {
            DatabaseManager::initPointAddressConfig(id);
            dealer_handler_->sendRequest("select-all-substation", "");
            emit addNodeRequested(pid, id);
        }
    }

    if (method == "delete-substation")
    {
        int re = body.toInt();
        if (re > 0)
        {
            DatabaseManager::deletePointAddressConfig(re);
            dealer_handler_->sendRequest("select-all-substation", "");
        }
    }

    if (method == "update-substation")
    {
        int re = body.toInt();
        if (re > 0)
        {
            dealer_handler_->sendRequest("select-all-substation", "");
        }
    }
}

StateInfo *SearchTreeWidget::stateInfo()
{
    // 返回第一个主站的信息，如果没有则返回nullptr
    if (!state_group_vec_.isEmpty())
    {
        return state_group_vec_.first()->stateInfo();
    }
    return nullptr;
}

std::vector<StateInfo *> *SearchTreeWidget::stateInfoVec()
{
    // 创建一个临时vector来存储所有子站信息
    static std::vector<StateInfo *> all_child_states;
    all_child_states.clear();

    // 遍历所有主站组，收集所有子站信息
    for (auto group : state_group_vec_)
    {
        const QVector<StateInfo *> &child_states = group->stateInfosVec();
        all_child_states.insert(all_child_states.end(), child_states.begin(), child_states.end());
    }

    return &all_child_states;
}

void SearchTreeWidget::selectRootNode()
{
    QTreeWidgetItem *root_item = tree_widget_->topLevelItem(0);
    if (root_item)
    {
        tree_widget_->setCurrentItem(root_item);
    }
}

StateGroup *SearchTreeWidget::stateGroupVec(int index)
{
    if (index < 0 || index >= state_group_vec_.size())
    {
        return nullptr;
    }
    return state_group_vec_[index];
}

int SearchTreeWidget::stateGroupVecSize()
{
    return state_group_vec_.size();
}

bool SearchTreeWidget::selectNodeByStateInfo(StateInfo* state_info)
{
    if (!state_info)
    {
        return false;
    }

    // 遍历所有节点查找匹配的节点
    QTreeWidgetItemIterator it(tree_widget_);
    while (*it)
    {
        int64_t node_id = (*it)->data(0, Qt::UserRole).toLongLong();
        if (node_id == state_info->id())
        {
            tree_widget_->setCurrentItem(*it);
            return true;
        }
        ++it;
    }

    return false;
}
